<script lang="ts" setup>
import { reactive, ref } from 'vue';
import { useMessage } from '/@/hooks/web/useMessage';
import {
  GetUserList,
  DeleteUsers,
  AssignAdmin,
  DeleteAdmin,
  UnlockUser,
  LockUser,
  downloadExcal,
} from '/@/api/user';
import UseOrganization from '/@/views/sys/organization/UseOrganization';
// import { Icon } from '/@/components/Icon';
import AddUserModal from './AddUserModal.vue';
import AddUser2OrgModal from './AddUser2Org.vue';
import RoleDrawer from './RoleDrawer.vue';
import DataDrawer from './DataDrawer.vue';
import LineDrawer from './LineDrawer.vue';
import ResourceDrawer from './ResourceDrawer.vue';
import { ElMessage, genFileId } from 'element-plus';
// import { usePermissionStore } from '/@/store/modules/permission';
import { useGlobSetting } from '/@/hooks/setting';
import { getToken } from '/@/utils/auth';

const globSetting = useGlobSetting();
const apiUrl = globSetting.apiUrl;

// 用户权限关联字段
// const permissionStore = usePermissionStore();
// console.log('permissionStore', permissionStore.getPermCodeList)
// const isAdminAssign = permissionStore.getPermCodeList.includes('administrator:add')
// console.log('isAdminAssign', isAdminAssign)
// const isAdminDell = permissionStore.getPermCodeList.includes('administrator:delete')

const { createMessage } = useMessage();
const loading1 = ref(false);
const state = reactive({
  loading: false,
});

const searchFormRef = ref();
const searchForm = reactive({
  username: '',
  userNo: '',
  longNo: '',
  mobile: '',
  email: '',
  orgId: null,
});
const searchFormActions = {
  async onSearch() {
    tableActions.getList();
  },
  resetFields() {
    searchFormRef.value.resetFields();
    tableActions.getList();
  },
  clearOrgSelect() {
    currentOrg.value = null;
    searchForm.orgId = null;
    tableActions.getList();
  },
};

const { organizations } = UseOrganization(loading1);
const currentOrg = ref();
const treeActions = {
  selected: (data) => {
    if (data.orgId) {
      searchForm.orgId = data.orgId;
      currentOrg.value = data;
    } else {
      searchForm.orgId = null;
    }
    searchFormActions.onSearch();
  },
  importUser: (orgId) => {
    modal.data = orgId;
    modalActions.show();
  },
};

const table = reactive({
  data: [],
  selected: [] as any,
});

const token = getToken();

const headers = {
  Authorization: token,
};

const handleUploadSuccess = (data: any) => {
  if (data.code == 200) {
    ElMessage.success(data.msg);
    searchFormActions.onSearch();
  } else {
    ElMessage.error(data.msg);
  }
};

const tableActions = {
  async getList() {
    state.loading = true;
    let params = {
      startIndex: pg.current,
      pageSize: pg.size,
      username: searchForm.username,
      userNo: searchForm.userNo,
      longNo: searchForm.longNo,
      email: searchForm.email,
      mobile: searchForm.mobile,
      orgId: searchForm.orgId,
    };
    let { data, code, msg } = await GetUserList(params);
    state.loading = false;
    table.data = [];
    if (code === 200) {
      table.data = data.list;
      table.data.forEach((el: any) => {
        el.lockFlag = el.lockFlag == 1 ? '已锁定' : '有效';
      });
      pg.total = data.total;
      table.selected = [];
    } else {
      createMessage({
        message: msg,
        type: 'error',
      });
    }
  },
  selectionChange(v) {
    table.selected = v;
  },
  create() {
    modal.data = undefined;
    modalActions.show();
  },
  update(r) {
    modal1.data = r;
    modal1Actions.show();
  },
  delete(r) {
    deleteReq({ userIds: [r.id], orgId: r?.orgId });
  },
  batchDel() {
    let ids = table.selected.map((e) => e.id);
    let orgIds = table.selected.map((e) => e.orgId);
    deleteReq({ userIds: ids, orgIds: orgIds });
  },
  batchAssign() {
    let ids = [];
    table.selected.forEach((e) => {
      if (e.adminFlag == 0) {
        ids.push(e.id);
      }
    });
    if (ids.length > 0) {
      assignAll({ userIds: ids });
    } else {
      ElMessage.error('请选择可授权的用户！');
    }
  },
  batchDelAdmin() {
    let ids = [];
    table.selected.forEach((e) => {
      if (e.adminFlag == 1) {
        ids.push(e.id);
      }
    });
    if (ids.length > 0) {
      deleteAssign({ userIds: ids });
    } else {
      ElMessage.error('请选择可移除的用户！');
    }
    // let ids = table.selected.map((e) => {
    //   if (e.adminFlag == 1) return e.id
    // });
    // deleteAssign({ userIds: ids });
  },
  updateRole(r) {
    modal2.data = r;
    modal2Actions.show();
  },
  updateDataPermission(r) {
    modal3.data = r;
    modal3Actions.show();
  },
  updateLinePermission(r) {
    modal4.data = r;
    modal4Actions.show();
  },
  updateResourcePermission(r) {
    modal5.data = r;
    modal5Actions.show();
  },
  async lock(r) {
    let { data, code, msg } = await LockUser({ userId: r.id, lockFlag: 1 });
    if (code == 200) {
      ElMessage.success(msg);
      searchFormActions.onSearch();
    } else {
      ElMessage.error(msg);
    }
  },
  async unlock(r) {
    let { data, code, msg } = await UnlockUser({ userId: r.id, lockFlag: 0 });
    if (code == 200) {
      ElMessage.success(msg);
      searchFormActions.onSearch();
    } else {
      ElMessage.error(msg);
    }
  },
  download() {
    btnLoading2.value = true;
    downloadExcal();
    setTimeout(() => {
      btnLoading2.value = false;
    }, 10000);
  },
};

let btnLoading2 = ref(false);

const pg = reactive({
  current: 1,
  size: 20,
  total: 0,
});

const pgActions = {
  resetPg: () => {
    pg.current = 1;
    pg.size = 20;
    pg.total = 0;
  },
  currentChange(r) {
    pg.current = r;
    searchFormActions.onSearch();
  },
  sizeChange(r) {
    pg.current = 1;
    pg.size = r;
    searchFormActions.onSearch();
  },
};

const modal = reactive({
  visible: false,
  data: undefined,
});

const modalActions = {
  success() {
    pg.current = 1;
    searchFormActions.onSearch();
  },
  show() {
    modal.visible = true;
  },
};

const modal1 = reactive({
  visible: false,
  data: undefined,
});

const modal1Actions = {
  success() {
    pg.current = 1;
    searchFormActions.onSearch();
  },
  show() {
    modal1.visible = true;
  },
};

const modal2 = reactive({
  visible: false,
  data: undefined as any,
});

const modal2Actions = {
  success() {
    searchFormActions.onSearch();
  },
  show() {
    modal2.visible = true;
  },
};

const modal3 = reactive({
  visible: false,
  data: undefined as any,
});

const modal3Actions = {
  success() {
    searchFormActions.onSearch();
  },
  show() {
    modal3.visible = true;
  },
};

const modal4 = reactive({
  visible: false,
  data: undefined,
});

const modal4Actions = {
  success() {
    pg.current = 1;
    searchFormActions.onSearch();
  },
  show() {
    modal4.visible = true;
  },
};

const modal5 = reactive({
  visible: false,
  data: undefined,
});

const modal5Actions = {
  success() {
    pg.current = 1;
    searchFormActions.onSearch();
  },
  show() {
    modal5.visible = true;
  },
};

// req
async function deleteReq(p) {
  state.loading = true;
  try {
    const { code, msg } = await DeleteUsers(p);
    state.loading = false;
    if (code == 200) {
      createMessage({
        message: msg,
      });
      searchFormActions.onSearch();
    }
  } catch {
    state.loading = false;
  }
}

// req
async function assignAll(p) {
  state.loading = true;
  try {
    const { code, msg } = await AssignAdmin(p);
    state.loading = false;
    if (code == 200) {
      createMessage({
        message: msg,
      });
      searchFormActions.onSearch();
    }
  } catch {
    state.loading = false;
  }
}

// req
async function deleteAssign(p) {
  state.loading = true;
  try {
    const { code, msg } = await DeleteAdmin(p);
    state.loading = false;
    if (code == 200) {
      createMessage({
        message: msg,
      });
      searchFormActions.onSearch();
    }
  } catch {
    state.loading = false;
  }
}

searchFormActions.onSearch();
const upload = ref<UploadInstance>();

const handleUploadError = (err: any) => {
  const message = JSON.parse(err.toString().replace('UploadAjaxError: ', '')).msg;
  ElMessage.error(message);
};

const handleExceed = (files: any) => {
  upload.value!.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  upload.value!.handleStart(file);
  upload.value!.submit();
};
</script>

<template>
  <div class="p-4 menu-management h-0 flex-shrink-0">
    <div class="searchBox px-4 pt-4">
      <el-form :model="searchForm" ref="searchFormRef" inline label-width="90px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="searchForm.username" placeholder="请输入用户名" clearable />
        </el-form-item>
        <el-form-item label="用户编号" prop="userNo">
          <el-input v-model="searchForm.userNo" placeholder="请输入用户编号" clearable />
        </el-form-item>
        <!-- <el-form-item label="SF长工号" prop="longNo">
          <el-input v-model="searchForm.longNo" placeholder="请输入SF长工号" clearable />
        </el-form-item> -->
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="searchForm.mobile" placeholder="请输入手机号码" clearable />
        </el-form-item>
        <el-form-item label="电子邮箱" prop="email">
          <el-input v-model="searchForm.email" placeholder="请输入电子邮箱" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchFormActions.onSearch" :loading="state.loading">查询</el-button>
          <el-button @click="searchFormActions.resetFields">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="middle-content p-4 flex">
      <el-tree v-loading="loading1" class="mr-12 py-12 px-4 overflow-auto org-tree" :data="organizations"
        @node-click="treeActions.selected">
        <template #default="{ data }">
          <div class="w-full flex justify-start">
            <span style="overflow: hidden; white-space: nowrap; text-overflow: ellipsis" class="flex-grow">{{ data.label
              }}</span>
            <!-- <Icon
              icon="gg:import"
              @click.stop="treeActions.importUser(data.value)"
              style="flex: 14px 0 0"
              class="ml-4"
            /> -->
          </div>
        </template>
      </el-tree>
      <div class="sub-content flex-auto overflow-auto">
        <!-- <div class="tools mb-4">
          <div class="toolBtns">
            <el-popconfirm title="确定要删除吗？" @confirm="tableActions.batchDel" confirm-button-text="确定"
              cancel-button-text="取消">
              <template #reference>
                <el-button link :disabled="table.selected.length == 0">
                  <Icon icon="ep:delete" />批量删除
                </el-button>
              </template>
            </el-popconfirm>
            <el-popconfirm 
              title="确定要授权吗？" 
              @confirm="tableActions.batchAssign" 
              confirm-button-text="确定"
              cancel-button-text="取消"
            >
              <template #reference>
                <el-button link :disabled="table.selected.length == 0">
                  <Icon icon="ep:plus" />批量授权管理员
                </el-button>
              </template>
            </el-popconfirm>
            <el-popconfirm 
              title="确定要删除授权吗？" 
              @confirm="tableActions.batchDelAdmin" 
              confirm-button-text="确定"
              cancel-button-text="取消"
            >
              <template #reference>
                <el-button link :disabled="table.selected.length == 0">
                  <Icon icon="ep:delete" />批量删除管理员
                </el-button>
              </template>
            </el-popconfirm>
          </div>
          <div class="selected">
            已选择<span class="blue">{{ table.selected.length }} 项</span>
          </div>
        </div> -->
        <div class="mb-4">
          <el-tag type="success" :closable="!!currentOrg" @close="searchFormActions.clearOrgSelect">
            {{ currentOrg ? currentOrg?.label : '全部' }}
          </el-tag>

          <el-upload ref="upload" accept=".xls,xlsx,.XLS,.XLSX" :action="`${apiUrl}/user/import`" :headers="headers"
            :on-success="(data: any, uploadFile: any) => handleUploadSuccess(data, uploadFile)"
            :on-error="handleUploadError" :on-exceed="handleExceed" :show-file-list="false" name="file" :limit="1"
            style="float: right; margin-right: 10px" auto-upload>
            <el-button type="primary"> 导入用户 </el-button>
          </el-upload>
          <el-button type="primary" @click="tableActions.download" :loading="btnLoading2"
            style="float: right; margin-right: 10px">
            <ExportOutlined />
            导入模板下载
          </el-button>
        </div>
        <el-table class="mb-4" v-loading="state.loading" :data="table.data" row-key="id"
          :header-cell-style="{ background: '#f1f3f7' }">
          <!-- <el-table-column type="selection" width="55" fixed /> -->
          <el-table-column prop="username" label="用户名" :width="120" fixed show-overflow-tooltip />
          <el-table-column prop="userNo" label="用户编号" :width="160" show-overflow-tooltip />
          <!-- <el-table-column prop="longNo" label="SF长工号" :width="120" show-overflow-tooltip /> -->
          <el-table-column prop="mobile" label="手机号码" :width="120" />
          <el-table-column prop="email" label="电子邮箱" :width="180" show-overflow-tooltip />
          <el-table-column prop="" label="角色" :width="100" show-overflow-tooltip>
            <template #default="scope">
              <el-tag type="success" v-for="item in scope.row.roleVOList" class="mr-1 mb-1">{{ item.roleName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="email" label="管理员" :width="220" show-overflow-tooltip>
            <template #default="scope">
              <span>{{ scope.row.adminFlag == 1 ? '是' : '否' }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="" label="数据权限" :width="220" show-overflow-tooltip>
            <template #default="scope">
              <el-tag type="success" v-for="item in scope.row.dataPermissionModelList" class="mr-1 mb-1">{{ item.name }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="" label="资源权限" :width="220" show-overflow-tooltip>
            <template #default="scope">
              <el-tag type="success" v-for="item in scope.row.clientManagerModelList" class="mr-1 mb-1">{{ item }}
              </el-tag>
            </template>
          </el-table-column> -->
          <el-table-column prop="lockFlag" label="状态" :width="90" />
          <el-table-column prop="orgName" label="组织机构" :width="160" show-overflow-tooltip />
          <el-table-column prop="department" label="部门" :width="160" show-overflow-tooltip />
          <el-table-column prop="remark" label="备注" />
          <el-table-column prop="operation" label="操作" :width="530" fixed="right">
            <template #default="scope">
              <el-button link type="primary" @click="tableActions.updateRole(scope.row)">角色</el-button>
              <!-- <el-button link type="primary" @click="tableActions.updateDataPermission(scope.row)">数据权限</el-button> -->
              <el-button link type="primary" @click="tableActions.updateLinePermission(scope.row)">行级权限</el-button>
              <el-button link type="primary" @click="tableActions.updateResourcePermission(scope.row)">资源权限</el-button>
              <el-popconfirm v-if="scope.row.adminFlag == 1" title="确定要移除管理员吗？"
                @confirm="deleteAssign({ userIds: [scope.row.id] })" confirm-button-text="确定" cancel-button-text="取消">
                <template #reference>
                  <el-button link type="success">移除管理员</el-button>
                </template>
              </el-popconfirm>
              <el-popconfirm v-else title="确定要授权管理员吗？" @confirm="assignAll({ userIds: [scope.row.id] })"
                confirm-button-text="确定" cancel-button-text="取消">
                <template #reference>
                  <el-button link type="danger">授权管理员</el-button>
                </template>
              </el-popconfirm>
              <el-button link type="primary" @click="tableActions.update(scope.row)" v-if="scope.row.autoFlag != 1">编辑
              </el-button>
              <el-popconfirm v-if="scope.row.lockFlag == '有效'" title="确定要锁定吗？" @confirm="tableActions.lock(scope.row)"
                confirm-button-text="确定" cancel-button-text="取消">
                <template #reference>
                  <el-button link type="danger">锁定</el-button>
                </template>
              </el-popconfirm>
              <el-popconfirm v-if="scope.row.lockFlag == '已锁定'" title="确定要解锁吗？"
                @confirm="tableActions.unlock(scope.row)" confirm-button-text="确定" cancel-button-text="取消">
                <template #reference>
                  <el-button link type="success">解锁</el-button>
                </template>
              </el-popconfirm>
              <el-popconfirm v-if="scope.row.autoFlag != 1" title="确定要删除吗？" @confirm="tableActions.delete(scope.row)"
                confirm-button-text="确定" cancel-button-text="取消">
                <template #reference>
                  <el-button link type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination class="flex justify-end" background layout="total, sizes, prev, pager, next" :total="pg.total"
          :current-page="pg.current" @size-change="pgActions.sizeChange" v-model:page-size="pg.size"
          @current-change="pgActions.currentChange" :page-sizes="[20, 30, 50]" />
      </div>
    </div>
    <AddUserModal v-model:visible="modal1.visible" :data="modal1.data" :orgList="organizations" @success="modal1Actions.success" />
    <AddUser2OrgModal v-model:visible="modal.visible" :selectedOrgId="modal.data" :orgList="organizations" @success="modalActions.success" />
    <RoleDrawer v-model:visible="modal2.visible" :user="modal2.data" @success="modal2Actions.success" />
    <DataDrawer v-model:visible="modal3.visible" :user="modal3.data" @success="modal3Actions.success" />
    <LineDrawer v-model:visible="modal4.visible" :user="modal4.data" @success="modal4Actions.success" />
    <ResourceDrawer v-model:visible="modal5.visible" :user="modal5.data" @success="modal5Actions.success" />
  </div>
</template>

<style lang="less" scoped>
html[data-theme='light'] {

  .searchBox,
  .middle-content {
    background-color: #fff;
  }
}

html[data-theme='dark'] {

  .searchBox,
  .middle-content {
    background-color: #151515;
  }
}

.el-table {
  height: calc(100vh - 400px);
}

.menu-management {
  min-height: 100%;
  display: flex;
  flex-direction: column;

  .middle-content {
    flex: 1;

    .org-tree {
      flex: 0 0 300px;
    }

    .sub-content {
      width: calc(100% - 290px);

      .tools {
        display: flex;
        justify-content: space-between;

        .selected {
          line-height: 32px;

          .blue {
            margin-left: 5px;
            color: #237ae4;
          }
        }
      }
    }

    :deep(.el-tree-node__label) {
      flex: 1;
    }
  }
}

// :deep(.el-tree-node__label) {
//   width: 0;
// }</style>
